package com.pig4cloud.pigx.common.security.service;

import com.pig4cloud.pigx.admin.api.entity.ToCUser;
import com.pig4cloud.pigx.admin.api.feign.RippleRemoteUserService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.grant.api.ApiTokenGranter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Objects;


/**
 * Api鉴权查询用户信息实现类
 *
 * @since 2022/11/7 17:14
 */
@RequiredArgsConstructor
public class RippleApiUserDetailsServiceImpl implements PigxUserDetailsService {

    private final RippleRemoteUserService remoteUserService;

    /**
     * api鉴权时查询用户信息
     *
     * @param accessKey AccessKey
     * @return {@link UserDetails}
     * @since 2022/11/7 18:02
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String accessKey) {
        ToCUser user = remoteUserService.userInfoByAccessKey(accessKey, SecurityConstants.FROM_IN).getData();
        if (Objects.isNull(user)) {
            // 无效的AccessKey
            throw new RuntimeException("Invalid API-key, IP, or permissions for action.");
        }

        //判断用户是否禁用
        boolean enabled = !user.getStatus().equals(1);

        // 用户名会作为Authentication.getName()的返回参数，校验token时重新根据这个值查询用户信息
        return new PigxUser(Long.valueOf(user.getUid()), accessKey, null,
                "Phone", "Avatar", user.getUid(),
                user.getUid(), user.getEmail(), 1L,
                "{noop}" + user.getAddress(), enabled, true,
                true, true, AuthorityUtils.NO_AUTHORITIES,
                user.getLanguageCode());
    }

    // check-token 校验token使用
    @Override
    public UserDetails loadUserByUser(PigxUser pigxUser) {
        // 根据 pigxUser 里面的信息 查询对应表 返回 UserDetails，pigxUser.getUsername()为数据库存储的 授权钱包地址
        return this.loadUserByUsername(pigxUser.getUsername());
    }

    @Override
    public boolean support(String clientId, String grantType) {
        return ApiTokenGranter.CLIENT_ID.equals(clientId);
    }

    /**
     * 排序值
     *
     * @return 排序值
     */
    @Override
    public int getOrder() {
        return 20;
    }

}


